from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

from . import serializers
from .models import User

# GET usernames/(?P<username>\w{5,20})/count/
class UserNameCountView(APIView):
    """校验用户名是否已经存在"""
    def get(self, request, username):
        count = User.objects.filter(username=username, is_active=True).count()
        data = {
            "username": username,
            "count": count
        }
        return Response(data=data)

# GET mobiles/(?P<mobile>1[3-9]\d{9})/count
class UserMobileCountView(APIView):
    """校验手校号是否已经存在"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile, is_active=True).count()
        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data=data)

# POST /users/
class UserRegisterView(CreateAPIView):
    """用户注册类视图"""
    serializer_class = serializers.UserRegisterSerializer


# GET /user/
# 返回 user_id username email email_active mobile
class UserInfoView(RetrieveAPIView):
    """用户个人详情页"""
    serializer_class = serializers.UserInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        user = self.request.user
        return user


# POST /email/
# 返回id email / 更新user, 发送邮件
class EmailBindingView(UpdateAPIView):
    """用户绑定邮箱"""
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailBindingSerializer

    def get_object(self):
        user = self.request.user
        return user

# PUT /emails/verification/
# 更新user的email_active
class EmailsVerificationView(APIView):
    """邮件验证视图"""
    def get(self, request):
        token = request.query_params.get("token")
        if not token:
            return Response(data={"message":"无效的验证链接"}, status=status.HTTP_400_BAD_REQUEST)

        user = User.check_email_binding(token)
        if not user:
            return Response(data={"message":"邮箱校验失败"}, status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()
        return Response({"message":"OK"})
